package com.njbw.design_pattern.struct.proxy.dynamicProxy.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 *
 * @author 黄侯淳
 * @since JDK 1.8
 */
@Slf4j
@Aspect
@Component
public class CacheAspectJ {

    @Pointcut("execution(* com.njbw.design_pattern.struct.proxy.dynamicProxy.aop.DatabaseDataQuery.query(..))" )
    public void pointcut() {}

    @Around("pointcut()")
    public String around(ProceedingJoinPoint joinPoint) {
        // 获取方法参数列表
        Object[] args = joinPoint.getArgs();
        String cacheKey = args[0].toString();
        // 1.查询缓存命中则直接返回
        String result = Cache.get(cacheKey);
        if (null != result) {
            log.info("缓存命中，直接返回缓存结果...");
            return result;
        }
        // 2.缓存未命中则去查询数据库，实际上是调用被代理 bean 的方法
        log.info("缓存未命中，查询数据库...");
        try {
            result = joinPoint.proceed(args).toString();
            if (null != result) {
                Cache.put(cacheKey, result);
            }
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}
